package com.yk.print.controller;

import cn.hutool.core.date.DateUtil;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.yk.print.model.SnInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("")
public class BartenderPrint {

    @PostMapping(value = "/print")
    protected String print(@RequestBody List<SnInfo> snInfos)  {
        //要运行COM组件，需要先将jacob-1.19-x64.dll放到jdk的bin目录下，不然会报错。如果是32位jdk放入32位的dll文件
        ComThread.InitSTA();
        //加载Bartender进程，需要先安装Bartender，我安装的是BT2019R4版本。
        ActiveXComponent btApp = new ActiveXComponent("BarTender.Application");

        //加载Bartender模板控件
        Dispatch btFormats = btApp.getProperty("Formats").toDispatch();
        //调用模板
        Dispatch btFormat = Dispatch.call(btFormats, "Open", "C:\\WmsBarTenderPrint\\model\\SN.btw", false, "").toDispatch();
        for (SnInfo snInfo : snInfos) {
            log.info("{} 打印条码：{}",DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"),snInfo.getSn());
            //传递参数，参数名称要和Bartender中设置的名称一样，不然会失败
            Dispatch.call(btFormat, "SetNamedSubStringValue", "SN", snInfo.getSn());
            Dispatch.call(btFormat, "SetNamedSubStringValue", "QTY", snInfo.getQty());
            Dispatch.call(btFormat, "SetNamedSubStringValue", "pdate", DateUtil.format(snInfo.getPdate(),"yy/MM/dd"));
            Dispatch.call(btFormat, "SetNamedSubStringValue", "ItemCode",snInfo.getItemCode());

            //设置打印份数，默认是1份可以不设置
            Dispatch printSetup = Dispatch.get(btFormat, "PrintSetup").toDispatch();
            Dispatch.put(printSetup, "IdenticalCopiesOfLabel", 1);

            //打印，Bartender会自动选择模板中设置的打印机打印
            Dispatch.call(btFormat, "PrintOut", false, false);
        }

        //打印完成，关闭模板控件
        Dispatch.call(btFormat, "Close", 0);

        //关闭Bartender进程
        Dispatch.call(btApp, "Quit", 0);
        ComThread.Release();
        return "打印成功";
    }

}
